﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using DataAccess.Interfaces;

namespace DataAccess
{
    [Export(typeof(ITermRepository))]
    public class TermRepository : ITermRepository
    {
        private Connection conn;

        public TermRepository()
        {
            conn = new Connection();
        }

        public Term GetCurrentTerm()
        {
            using (SimmEntities dc = conn.getEntities())
            {
                Term term = (from t in dc.Term
                             orderby t.CreateDate descending
                             select t).FirstOrDefault();
                return term;

            }
        }

        public void SaveTerm(Term term)
        {
            using (SimmEntities dc = conn.getEntities())
            {
                if (term.TermID > 0)
                {
                    dc.Term.AddObject(term);
                }
                else
                {
                    dc.Term.ApplyCurrentValues(term);
                }
                dc.SaveChanges();
            }
        }

        public void DeleteTerm(Term term)
        {
            using (SimmEntities dc = conn.getEntities())
            {
                dc.DeleteObject(dc.Term.Where(t => t.TermID.Equals(term.TermID)).FirstOrDefault());
                dc.SaveChanges();
            }
        }
    }
}
